<template>
  <el-dialog
    v-model="dialogVisible"
    title="创建订单"
    width="900px"
    @close="handleClose"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form 
      ref="orderFormRef"
      :model="formData" 
      label-width="80px"
      :rules="formRules"
      validate-on-rule-change
    >
      <!-- 客户信息 -->
      <el-form-item label="客户姓名" prop="customer_name" required>
        <el-input
          v-model="formData.customer_name"
          placeholder="请输入客户姓名"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="客户电话" prop="customer_phone" required>
        <el-input
          v-model="formData.customer_phone"
          placeholder="请输入客户电话"
          maxlength="20"
          type="tel"
          show-word-limit
          @input="handlePhoneInput"
        />
      </el-form-item>

      <el-form-item label="下单时间" prop="order_time">
        <el-date-picker
          v-model="formData.order_time"
          type="datetime"
          placeholder="选择下单时间"
          style="width: 100%;"
          :default-time="['12:00:00']"
        />
      </el-form-item>

      <!-- 商品明细 -->
      <el-form-item label="商品明细" required>
        <div class="items-container">
          <!-- 添加商品表单 -->
          <div class="add-item-form">
            <el-input
              v-model="itemForm.name"
              placeholder="商品名称"
              style="width: 28%; margin-right: 10px;"
              maxlength="100"
              show-word-limit
            />
            <span style="margin-right: 5px;">数量:</span>
            <el-input-number
              v-model="itemForm.quantity"
              :min="1"
              style="margin-right: 30px;"
              :precision="0"
            />
            <span style="margin-right: 5px;">单价:</span>
            <el-input-number
              v-model="itemForm.price"
              :min="0"
              :step="0.01"
              style="margin-right: 10px;"
              :precision="2"
            />
            <el-button 
              type="primary" 
              @click="addItem"
              :disabled="!canAddItem"
              :loading="addingItem"
            >
              添加
            </el-button>
          </div>

          <!-- 商品列表 -->
          <el-table
            v-if="formData.items.length > 0"
            :data="formData.items"
            style="margin-top: 20px;"
            stripe
          >
            <el-table-column prop="name" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="quantity" label="数量" width="150">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.quantity"
                  :min="1"
                  @change="updateItemQuantity(scope.$index, $event)"
                  size="small"
                  :precision="0"
                />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="150">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.price"
                  :min="0"
                  :step="0.01"
                  @change="updateItemPrice(scope.$index, $event)"
                  size="small"
                  :precision="2"
                />
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="小计" width="120">
              <template #default="scope">
                ¥{{ scope.row.subtotal.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right">
              <template #default="scope">
                <el-button
                  type="danger"
                  text
                  @click="handleRemoveItem(scope.$index, scope.row.name)"
                  :disabled="loading"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
      <div v-else class="empty-items">
        <el-empty description="暂无商品，请添加商品" :image-size="100" />
      </div>
        </div>
      </el-form-item>

      <!-- 订单总价 -->
      <el-form-item>
        <div class="total-price">
          <span>订单总价：</span>
          <span class="price">¥{{ calculateTotal().toFixed(2) }}</span>
          <span class="item-count">（共 {{ formData.items.length }} 件商品）</span>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose" :disabled="loading">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleSubmit" 
        :loading="loading"
        :disabled="!canSubmit"
      >
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useOrderForm } from '../hooks/useOrderForm';

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

// Emits
const emit = defineEmits(['update:modelValue', 'success']);

// 表单引用
const orderFormRef = ref(null);

// 使用订单表单hook
const { formData, loading, itemForm, addItem, removeItem, updateItemQuantity, updateItemPrice, calculateTotal, submitForm, resetForm } = useOrderForm();

// 表单规则
const formRules = ref({
  customer_name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '客户姓名长度在1-50个字符之间', trigger: 'blur' }
  ],
  customer_phone: [
    { required: true, message: '请输入客户电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  order_time: [
    { required: true, message: '请选择下单时间', trigger: 'change' }
  ]
});

// 添加商品状态
const addingItem = ref(false);

// 对话框可见性
const dialogVisible = ref(props.modelValue);

// 计算属性：是否可以添加商品
const canAddItem = computed(() => {
  return itemForm.name?.trim() && itemForm.quantity > 0 && itemForm.price >= 0;
});

// 计算属性：是否可以提交表单
const canSubmit = computed(() => {
  return formData.customer_name?.trim() && 
         formData.customer_phone?.trim() && 
         formData.order_time && 
         formData.items.length > 0;
});

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal;
  if (newVal) {
    // 打开对话框时设置默认时间
    if (!formData.order_time) {
      formData.order_time = new Date();
    }
  }
});

// 处理电话号码输入
const handlePhoneInput = (value) => {
  // 只允许输入数字
  formData.customer_phone = value.replace(/[^0-9]/g, '');
};

// 处理移除商品
const handleRemoveItem = async (index, itemName) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品 "${itemName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    removeItem(index);
    ElMessage.success('商品已删除');
  } catch (error) {
    // 用户取消删除
  }
};

// 处理对话框关闭
const handleClose = () => {
  // 直接关闭对话框，不检查未保存的更改
  doClose();
};

// 执行关闭操作
const doClose = () => {
  resetForm();
  emit('update:modelValue', false);
};

// 检查是否有未保存的更改
const hasUnsavedChanges = () => {
  return formData.customer_name?.trim() || 
         formData.customer_phone?.trim() || 
         formData.items.length > 0;
};

// 处理表单提交
const handleSubmit = async () => {
  // 验证表单
  if (!orderFormRef.value) return;
  
  try {
    await orderFormRef.value.validate();
    
    // 验证商品列表
    if (formData.items.length === 0) {
      ElMessage.error('请至少添加一个商品');
      return;
    }
    
    const success = await submitForm();
    if (success) {
      ElMessage.success('订单创建成功');
      emit('success');
      emit('update:modelValue', false);
    }
  } catch (error) {
    // 表单验证失败
    ElMessage.error('请完善订单信息');
  }
};

// 生命周期钩子
onMounted(() => {
  // 初始化时设置默认时间
  if (!formData.order_time) {
    formData.order_time = new Date();
  }
});
</script>

<style scoped>
.items-container {
  max-height: 400px;
  overflow-y: auto;
}

.add-item-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.empty-items {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.total-price {
  text-align: right;
  font-size: 16px;
  font-weight: bold;
  margin-top: 20px;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}

.price {
  color: #f56c6c;
  font-size: 18px;
  margin: 0 8px;
}

.item-count {
  font-size: 14px;
  color: #909399;
  font-weight: normal;
}

.el-table {
  --el-table-header-bg-color: #fafafa;
}
</style>